package com.insmess.speech.sdk.template;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.insmess.speech.sdk.dto.AsrRequestDto;
import com.insmess.speech.sdk.dto.AsrResponseDto;
import com.insmess.speech.sdk.dto.TtsRequestDto;
import com.insmess.speech.sdk.dto.TtsResponseDto;
import com.insmess.speech.sdk.util.FileBase64Utils;
import lombok.SneakyThrows;

import java.io.File;
import java.util.UUID;

public class InsmessTtsTemplate {
    private String url;

    public InsmessTtsTemplate(String url) {
        this.url = url;
    }
    /**
     * TTS
     * @return
     */
    @SneakyThrows
    public TtsResponseDto ttsRequest(String text) {
        TtsRequestDto ttsRequestDto = new TtsRequestDto();
        ttsRequestDto.setText(text);
        ttsRequestDto.setVolume(1.0);
        ttsRequestDto.setSpeed(1.0);
        ttsRequestDto.setSpkId(0);
        ttsRequestDto.setSampleRate(0);
        TtsResponseDto ttsResponseDto = ttsRequest(ttsRequestDto);
        return ttsResponseDto;
    }
    /**
     * TTS
     * @return
     */
    @SneakyThrows
    public TtsResponseDto ttsRequest(TtsRequestDto ttsRequestDto) {
        ttsRequestDto.setSavePath("./tmp/" + UUID.randomUUID() + ".wav");
        HttpRequest http = HttpUtil.createPost(url);
        TtsResponseDto ttsResponseDto = getTtsResponseDto(http, ttsRequestDto);
        return ttsResponseDto;
    }
    /**
     * HTTP发送http请求并将结果转换
     * @param http
     * @param ttsRequestDto
     * @return
     * @throws JsonProcessingException
     */
    private TtsResponseDto getTtsResponseDto(HttpRequest http, TtsRequestDto ttsRequestDto) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        String json = objectMapper.writeValueAsString(ttsRequestDto);
        HttpResponse resp = http.body(json).execute();
        String body = resp.body();
        TtsResponseDto ttsResponseDto = objectMapper.readValue(body, TtsResponseDto.class);
        return ttsResponseDto;
    }
}
